package org.zachary.agent.infrastructure.repository;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
import org.zachary.agent.domain.aggregate_model.token.DeviceId;
import org.zachary.agent.domain.aggregate_model.token.RedisTokenEntity;
import org.zachary.agent.domain.aggregate_model.token.Token;
import org.zachary.agent.domain.repository.TokenRepository;


import java.util.Optional;
import java.util.concurrent.TimeUnit;

@Repository
public class RedisTokenRepository implements TokenRepository {
    private final RedisTemplate<String, RedisTokenEntity> redisTemplate;
    private static final String KEY_PREFIX = "refresh_token:";

    public RedisTokenRepository(RedisTemplate<String,RedisTokenEntity> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
    @Override
    public void save(Token token, String userId, DeviceId deviceId) {
        String key = buildKey(userId,deviceId);

        RedisTokenEntity entity=
                new RedisTokenEntity(
                        token.getId(),
                        token.getRefreshToken(),
                        token.getRefreshExpires(),
                        token.getStatus());



        redisTemplate.opsForValue().set(
                key,
                entity,
                token.getRefreshExpires(),
                TimeUnit.SECONDS
        );
    }
    @Override
    public Optional<RedisTokenEntity> findByUserIdAndDeviceId(String userId,DeviceId deviceId) {
        String key = buildKey(userId,deviceId);
        RedisTokenEntity data = redisTemplate.opsForValue().get(key);
        return Optional.ofNullable(data);
    }
    @Override
    public void invalidate(String userId,DeviceId deviceId) {
        redisTemplate.delete(buildKey(userId,deviceId));
    }
    private String buildKey(String userId,DeviceId device) {
        return KEY_PREFIX + userId + ":" + device.getDeviceId();
    }
}
